﻿using System;
using System.Collections.Generic;
using System.Text;

namespace IMLibrary.Audio
{
    /// <summary>
    ///  音频采集组件
    /// </summary>
    public class AudioCapturer
    {
        #region 变量
        /// <summary>
        /// 声音采集器
        /// </summary>
        private LumiSoft.Media.Wave.WaveIn m_pWaveIn = null;

        #endregion

        #region 事件

        /// <summary>
        /// 音频数据捕获事件
        /// </summary>
        /// <param name="sender">对像</param>
        /// <param name="e">音频采集事件参数类</param>
        public delegate void AudioDataCaptureredEventHandler(object sender, AudioCapturedEventArgs e);

        /// <summary>
        /// 音频数据捕获事件
        /// </summary>
        public event AudioDataCaptureredEventHandler AudioDataCapturered;

        #endregion

        #region 初始化
        /// <summary>
        /// 初始化音频采集组件
        /// </summary>
        public AudioCapturer()
        {
            try
            {
                m_pWaveIn = new LumiSoft.Media.Wave.WaveIn(LumiSoft.Media.Wave.WaveIn.Devices[0], 8000, 16,1,480);
                m_pWaveIn.BufferFull += new LumiSoft.Media.Wave.BufferFullHandler(m_pWaveIn_BufferFull);
                m_pWaveIn.Start();
            }
            catch { }
        } 
        #endregion 

        #region 关闭并释放资源
        /// <summary>
        /// 关闭并释放资源
        /// </summary>
        public void Close()
        {
            if (m_pWaveIn != null)
            {
                m_pWaveIn.Stop();
                m_pWaveIn.Dispose();
            } 
        }
        #endregion
         
        #region method m_pWaveIn_BufferFull
        /// <summary>
        /// This method is called when recording buffer is full and we need to process it.
        /// </summary>
        /// <param name="buffer">Recorded data.</param>
        private void m_pWaveIn_BufferFull(byte[] buffer)
        {
            if (AudioDataCapturered != null)
                this.AudioDataCapturered(this,new AudioCapturedEventArgs(buffer));
        }
        #endregion
    }

    #region 音频捕获事件参数
    /// <summary>
    ///  音频捕获事件参数
    /// </summary>
    public class AudioCapturedEventArgs : System.EventArgs
    {

        /// <summary>
        /// 捕获到的音频数据
        /// </summary>
        public byte[] Data;

        /// <summary>
        /// 初始化事件参数
        /// </summary>
        public AudioCapturedEventArgs()
        {

        }

        /// <summary>
        /// 初始化事件参数
        /// </summary>
        /// <param name="data">捕获的音频数据</param>
        public AudioCapturedEventArgs(byte[] data)
        {
            this.Data = data;
        } 
    }
    #endregion
}
